package com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.config.WxPayConfig;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.entity.WxPayFunctions;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.req.RxRegistrationChargeCategoryRecordDetailReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.req.RxRegistrationChargeCategoryRecordReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryDetailResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryRecordResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.service.RxRegistrationChargeCategoryRecordService;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.RxRegistrationAdvanceStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.req.RxRegistrationAdvanceCustomColumnValueReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.resp.RxRegistrationAdvanceCustomColumnValueResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.mapper.RxRegistrationAdvanceStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.req.RxRegistrationChargePaymentCategoryDivideReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.req.RxRegistrationChargePaymentRecordReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.resp.RxRegistrationPrepayPaymentResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.util.PaymentUtil;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.entity.RxRegistrationConfirm;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.entity.req.RxRegistrationConfirmPaymentReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.entity.resp.RxRegistrationConfirmResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.mapper.RxRegistrationConfirmMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationConfirm.service.RxRegistrationConfirmService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationExamine.entity.RxRegistrationExamineBlackList;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationExamine.mapper.RxRegistrationExamineBlackListMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationPlanChargeCategoryResp;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum.RX_REGISTRATION_ADVANCE_NOT_SUBMIT;
import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.AppTypeConstant.APP_TYPE_ADVANCE;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.AppTypeConstant.APP_TYPE_CONFIRM;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.ChargeCategoryTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.PlanStatusConstant.PLAN_STATUS_ENABLE;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.constant.RegistrationStatusConstant.REGISTRATION_STATUS_FINISH;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.constant.PaymentTypeConstant.*;

/**
 * <p>
 * 确认招生阶段 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-05-18
 */
@Service
public class RxRegistrationConfirmServiceImpl extends ServiceImpl<RxRegistrationConfirmMapper, RxRegistrationConfirm> implements RxRegistrationConfirmService {
    @Resource
    private RxRegistrationAdvanceStudentInfoMapper rxRegistrationAdvanceStudentInfoMapper;
    @Resource
    private RxRegistrationExamineBlackListMapper rxRegistrationExamineBlackListMapper;
    @Resource
    private RxRegistrationPlanSettingMapper rxRegistrationPlanSettingMapper;
    @Resource
    private RxRegistrationPlanAppSettingMapper rxRegistrationPlanAppSettingMapper;
    @Resource
    private RxRegistrationPlanChargeCategorySettingMapper rxRegistrationPlanChargeCategorySettingMapper;
    @Resource
    private RxRegistrationCustomColumnMapper rxRegistrationCustomColumnMapper;
    @Resource
    private RxRegistrationCustomColumnValueMapper rxRegistrationCustomColumnValueMapper;
    @Resource
    private PaymentUtil paymentUtil;
    @Resource
    private RxRegistrationChargeCategoryRecordMapper rxRegistrationChargeCategoryRecordMapper;
    @Resource
    private RxRegistrationChargeCategoryDetailMapper rxRegistrationChargeCategoryDetailMapper;
    @Resource
    private RxRegistrationChargeCategoryRecordService rxRegistrationChargeCategoryRecordService;

    @Override
    public ResponseResult getRegistrationConfirmStudentInfo(String stuIdCard) {
        boolean validIDCard = ParamCheckUtil.isValidIDCard(stuIdCard);
        if (!validIDCard) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_ID_CARD_ERR);
        }

        // 1.判断是否在黑名单中
        List<RxRegistrationExamineBlackList> blackList = rxRegistrationExamineBlackListMapper.selectList(new LambdaQueryWrapper<RxRegistrationExamineBlackList>()
                .eq(RxRegistrationExamineBlackList::getStuIdCard, stuIdCard));
        if (blackList != null && blackList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_STUDENT_BLACKLIST);
        }

        // 2.判断招生计划是否开启
        List<RxRegistrationPlanSetting> planSettingList = rxRegistrationPlanSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanSetting>()
                .eq(RxRegistrationPlanSetting::getPlanStatus, PLAN_STATUS_ENABLE));
        if (planSettingList == null || planSettingList.size() == 0) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_NOT_PLAN);
        }
        RxRegistrationPlanSetting planSetting = planSettingList.get(0);

        //获取招生计划下阶段招生开放时间
        Date nowDate = new Date();
        List<RxRegistrationPlanAppSetting> planAppSettingList = rxRegistrationPlanAppSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanAppSetting>()
                .eq(RxRegistrationPlanAppSetting::getPlanId, planSetting.getId())
                .lt(RxRegistrationPlanAppSetting::getBgTime, nowDate) //开始时间小于当前时间
                .gt(RxRegistrationPlanAppSetting::getEndTime, nowDate)  //结束时间大于当前时间
                .orderByDesc(RxRegistrationPlanAppSetting::getAppType));
        if (planAppSettingList == null || planAppSettingList.size() == 0) {
            return CommonResult.success(CommonCodeEnum.RX_REGISTRATION_CONFIRM_NOT_STEP);
        }

        RxRegistrationConfirmResp registrationConfirmResp = new RxRegistrationConfirmResp();

        List<RxRegistrationAdvanceStudentInfo> studentInfoList = rxRegistrationAdvanceStudentInfoMapper.selectList(new LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo>()
                .eq(RxRegistrationAdvanceStudentInfo::getIdCard, stuIdCard)
                .eq(RxRegistrationAdvanceStudentInfo::getPlanId, planSetting.getId()));

        //封装学生信息
        RxRegistrationAdvanceStudentInfo studentInfo = null;
        if (studentInfoList != null && studentInfoList.size() > 0) {
            //有学生信息
            studentInfo = studentInfoList.get(0);
            BeanUtils.copyProperties(studentInfo, registrationConfirmResp);
            registrationConfirmResp.setStuId(studentInfo.getId());
        } else {
            registrationConfirmResp.setPlanId(planSetting.getId());
        }

        //封装缴费项记录信息
        registrationConfirmResp.setChargeCategoryRecordRespList(getChargeCategoryRecordList(studentInfo));

        //封装缴费项信息
        registrationConfirmResp.setChargeCategoryRespList(getChargeCategoryRespList(planSetting.getId(), studentInfo));

        //封装自定义字段信息
        registrationConfirmResp.setCustomColumnValueList(getCustomColumnValueRespList(planSetting.getId(), studentInfo));
        return CommonResult.success(registrationConfirmResp);
    }

    private List<RxRegistrationPlanChargeCategoryResp> getChargeCategoryRespList(String planId,
                                                                                 RxRegistrationAdvanceStudentInfo studentInfo) {
        List<RxRegistrationPlanChargeCategoryResp> chargeCategoryRespList = new ArrayList<>();
        if (studentInfo != null
                && studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH
                && studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH) {
            return chargeCategoryRespList;
        }
        LambdaQueryWrapper<RxRegistrationPlanChargeCategorySetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RxRegistrationPlanChargeCategorySetting::getPlanId, planId)
                .and(wrapper -> {
                    if (studentInfo == null || studentInfo.getAdvanceStatus() != REGISTRATION_STATUS_FINISH) {
                        wrapper.eq(RxRegistrationPlanChargeCategorySetting::getAppType, APP_TYPE_ADVANCE);
                    }
                    if (studentInfo == null || studentInfo.getConfirmStatus() != REGISTRATION_STATUS_FINISH) {
                        wrapper.or()
                                .eq(RxRegistrationPlanChargeCategorySetting::getAppType, APP_TYPE_CONFIRM);
                    }
                })
                .orderByAsc(RxRegistrationPlanChargeCategorySetting::getAppType);
        List<RxRegistrationPlanChargeCategorySetting> settingList = rxRegistrationPlanChargeCategorySettingMapper.selectList(queryWrapper);
        chargeCategoryRespList = settingList
                .stream()
                .map(setting -> {
                    RxRegistrationPlanChargeCategoryResp chargeCategoryResp = new RxRegistrationPlanChargeCategoryResp();
                    BeanUtils.copyProperties(setting, chargeCategoryResp);

                    if (setting.getChargeCategoryType() != CHARGE_CATEGORY_TYPE_NORMAL) {
                        List<RxRegistrationChargeCategoryDetailResp> childList = JSONObject.parseArray(setting.getChargeCategoryChildren(), RxRegistrationChargeCategoryDetailResp.class);
                        chargeCategoryResp.setChildList(childList);
                    }
                    return chargeCategoryResp;
                }).collect(Collectors.toList());
        return chargeCategoryRespList;
    }

    private List<RxRegistrationChargeCategoryRecordResp> getChargeCategoryRecordList(RxRegistrationAdvanceStudentInfo studentInfo) {
        List<RxRegistrationChargeCategoryRecordResp> chargeCategoryRecordRespList = new ArrayList<>();
        LambdaQueryWrapper<RxRegistrationChargeCategoryRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (studentInfo == null) {
            return chargeCategoryRecordRespList;
        }
        queryWrapper.eq(RxRegistrationChargeCategoryRecord::getStuId, studentInfo.getId())
                .orderByAsc(RxRegistrationChargeCategoryRecord::getAppType);

        if (studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH
        || studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH){
            queryWrapper .and(wrapper -> {  //TODO
                if (studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH) {
                    wrapper.eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_ADVANCE);
                }
                if (studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH) {
                    wrapper.or()
                            .eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_CONFIRM);
                }
            });
        }else{
            return chargeCategoryRecordRespList;
        }

        chargeCategoryRecordRespList = rxRegistrationChargeCategoryRecordMapper.selectList(queryWrapper)
                .stream()
                .map(record -> {
                    RxRegistrationChargeCategoryRecordResp chargeCategoryResp = new RxRegistrationChargeCategoryRecordResp();
                    BeanUtils.copyProperties(record, chargeCategoryResp);
                    return chargeCategoryResp;
                })
                .collect(Collectors.toList());
        return chargeCategoryRecordRespList;
    }

    private List<RxRegistrationAdvanceCustomColumnValueResp> getCustomColumnValueRespList(String planId,
                                                                                          RxRegistrationAdvanceStudentInfo studentInfo) {
        List<RxRegistrationAdvanceCustomColumnValueResp> customColumnValueRespList;
        customColumnValueRespList = rxRegistrationCustomColumnMapper.selectList(new LambdaQueryWrapper<RxRegistrationCustomColumn>()
                        .eq(RxRegistrationCustomColumn::getPlanId, planId)
                        .and(wrapper -> {
                            wrapper.eq(RxRegistrationCustomColumn::getAppType, APP_TYPE_ADVANCE)
                                    .or()
                                    .eq(RxRegistrationCustomColumn::getAppType, APP_TYPE_CONFIRM);
                        })
                        .orderByAsc(RxRegistrationCustomColumn::getAppType)
                        .orderByAsc(RxRegistrationCustomColumn::getColumnSort))
                .stream()
                .map(column -> {
                    RxRegistrationAdvanceCustomColumnValueResp customColumnValueResp = new RxRegistrationAdvanceCustomColumnValueResp();
                    customColumnValueResp.setColumnName(column.getColumnName());
                    customColumnValueResp.setColumnSort(column.getColumnSort());
                    customColumnValueResp.setIsRequired(column.getIsRequired());
                    customColumnValueResp.setColumnId(column.getId());

                    //有学生信息 查询自定义字段数据
                    if (studentInfo != null) {
                        List<RxRegistrationCustomColumnValue> customColumnValues = rxRegistrationCustomColumnValueMapper.selectList(new LambdaQueryWrapper<RxRegistrationCustomColumnValue>()
                                .eq(RxRegistrationCustomColumnValue::getStudentId, studentInfo.getId())
                                .eq(RxRegistrationCustomColumnValue::getColumnId, column.getId()));
                        if (customColumnValues != null && customColumnValues.size() > 0) {
                            customColumnValueResp.setColumnValue(customColumnValues.get(0).getColumnValue());
                            customColumnValueResp.setId(customColumnValues.get(0).getId());
                        }
                    }
                    return customColumnValueResp;
                })
                .collect(Collectors.toList());
        return customColumnValueRespList;
    }

    @Override
    @Transactional
    public ResponseResult registrationConfirmPayment(RxRegistrationConfirmPaymentReq req) {
        if (isNullOrEmpty(req.getPlanId(), req.getName(),
                req.getMiddleSchool(), req.getMiddleSchoolId(), req.getIdCard(), req.getOpenId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验计划
        String planId = req.getPlanId();
        //查询计划是否存在并启用
        List<RxRegistrationPlanSetting> planSettingList = rxRegistrationPlanSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanSetting>()
                .eq(RxRegistrationPlanSetting::getId, planId)
                .eq(RxRegistrationPlanSetting::getPlanStatus, PLAN_STATUS_ENABLE));
        if (planSettingList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST);
        }
        //校验提交确认报名是否在计划有效期内
        List<RxRegistrationPlanAppSetting> appSettingList = rxRegistrationPlanAppSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanAppSetting>()
                .eq(RxRegistrationPlanAppSetting::getPlanId, planId)
                .eq(RxRegistrationPlanAppSetting::getAppType, APP_TYPE_CONFIRM));
        if (appSettingList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST);
        }
        RxRegistrationPlanAppSetting rxRegistrationPlanAppSetting = appSettingList.get(0);
        Date now = new Date();
        Date bgTime = rxRegistrationPlanAppSetting.getBgTime();
        Date endTime = rxRegistrationPlanAppSetting.getEndTime();
        //现在时间小于开始时间 或者大于结束时间则不允许提交
        if (now.compareTo(bgTime) < 0 || now.compareTo(endTime) > 0) {
            return CommonResult.failed(RX_REGISTRATION_ADVANCE_NOT_SUBMIT);
        }

        //校验身份证和电话
        boolean validIDCard = ParamCheckUtil.isValidIDCard(req.getIdCard());
        if (!validIDCard) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_ID_CARD_ERR);
        }
        boolean validPhone = ParamCheckUtil.isValidPhone(req.getTel());
        if (!validPhone) {
            return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_TEL_ERR);
        }


        //校验自定义字段
        List<RxRegistrationAdvanceCustomColumnValueReq> customColumnValueList = req.getCustomColumnValueList();//传入的自定义字段
        List<RxRegistrationCustomColumn> customColumnList = rxRegistrationCustomColumnMapper.selectList(new LambdaQueryWrapper<RxRegistrationCustomColumn>()
                .and(wrapper -> {
                    wrapper.eq(RxRegistrationCustomColumn::getAppType, APP_TYPE_CONFIRM)
                            .or()
                            .eq(RxRegistrationCustomColumn::getAppType, APP_TYPE_ADVANCE);
                })
                .eq(RxRegistrationCustomColumn::getPlanId, planId));//设置的自定义字段
        //设置了自定义字段
        if (customColumnList != null && customColumnList.size() > 0) {
            if (customColumnList.size() != customColumnValueList.size()) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }

            for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                if (rxRegistrationAdvanceCustomColumnValueReq.getIsRequired()) {
                    if (isNullOrEmpty(rxRegistrationAdvanceCustomColumnValueReq.getColumnValue(),rxRegistrationAdvanceCustomColumnValueReq.getColumnId())) {
                        ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_CUSTOM_COLUMN_NOT_SET));
                    }
                }

            }
        }

        //校验学生提交信息
        //已存在学生信息
        RxRegistrationAdvanceStudentInfo studentInfo = null;
        List<RxRegistrationAdvanceStudentInfo> studentInfoList = rxRegistrationAdvanceStudentInfoMapper.selectList(new LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo>()
                .eq(RxRegistrationAdvanceStudentInfo::getPlanId, planId)
                .eq(RxRegistrationAdvanceStudentInfo::getIdCard, req.getIdCard()));
        if (studentInfoList != null && studentInfoList.size() > 0){
            studentInfo = studentInfoList.get(0);
        }
        String stu_id;
        if (!isNullOrEmpty(studentInfo)) {
//            studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(req.getStuId());
//            if (studentInfo == null) {
//                return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_STUDENT_NOT_EXIST);
//            }

            //校验支付状态
            if (studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH && studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH) {
                return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_HAS_PAYED);
            }

            if (!studentInfo.getPlanId().equals(planId) || !studentInfo.getIdCard().equals(req.getIdCard())) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }

            RxRegistrationAdvanceStudentInfo updateStudentInfo = new RxRegistrationAdvanceStudentInfo();
            BeanUtils.copyProperties(req, updateStudentInfo);
            updateStudentInfo.setId(studentInfo.getId());
            rxRegistrationAdvanceStudentInfoMapper.updateById(updateStudentInfo);

            //修改该学生自定义信息
            if (customColumnValueList != null && customColumnValueList.size() > 0) {
                for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                    RxRegistrationCustomColumnValue rxRegistrationCustomColumnValue = new RxRegistrationCustomColumnValue();
                    BeanUtils.copyProperties(rxRegistrationAdvanceCustomColumnValueReq, rxRegistrationCustomColumnValue);

                    if (isNullOrEmpty(rxRegistrationAdvanceCustomColumnValueReq.getId())) {
                        rxRegistrationCustomColumnValue.setStudentId(studentInfo.getId());
                        rxRegistrationCustomColumnValue.setPlanId(planId);
                        rxRegistrationCustomColumnValueMapper.insert(rxRegistrationCustomColumnValue);
                    } else {
                        rxRegistrationCustomColumnValueMapper.update(rxRegistrationCustomColumnValue, new LambdaQueryWrapper<RxRegistrationCustomColumnValue>()
                                .eq(RxRegistrationCustomColumnValue::getPlanId, planId)
                                .eq(RxRegistrationCustomColumnValue::getStudentId, studentInfo.getId())
                                .eq(RxRegistrationCustomColumnValue::getColumnId, rxRegistrationAdvanceCustomColumnValueReq.getColumnId()));
                    }
                }
            }
        } else { //不存在学生信息
            RxRegistrationAdvanceStudentInfo addStudentInfo = new RxRegistrationAdvanceStudentInfo();
            BeanUtils.copyProperties(req, addStudentInfo);
            addStudentInfo.setPlanName(planSettingList.get(0).getPlanName());

            rxRegistrationAdvanceStudentInfoMapper.insert(addStudentInfo);
            studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(addStudentInfo.getId());

            //创建该学生自定义信息
            if (customColumnValueList != null && customColumnValueList.size() > 0) {
                for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                    RxRegistrationCustomColumnValue rxRegistrationAdvanceCustomColumnValue = new RxRegistrationCustomColumnValue();
                    BeanUtils.copyProperties(rxRegistrationAdvanceCustomColumnValueReq, rxRegistrationAdvanceCustomColumnValue);
                    rxRegistrationAdvanceCustomColumnValue.setStudentId(addStudentInfo.getId());
                    rxRegistrationAdvanceCustomColumnValue.setPlanId(planId);
                    rxRegistrationCustomColumnValueMapper.insert(rxRegistrationAdvanceCustomColumnValue);
                }
            }

        }
        stu_id = studentInfo.getId();

        //构造支付参数
        RxRegistrationChargePaymentRecordReq recordReq = new RxRegistrationChargePaymentRecordReq();
        List<RxRegistrationChargePaymentCategoryDivideReq> divideReqList = new ArrayList<>();

        // 获取商户集合
        List<WxPayFunctions> wxPayFunctionsList = WxPayConfig.wxPayFunctionsList;
        if (wxPayFunctionsList.isEmpty()) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        // 校验前端传入的商户Type
        RxRegistrationPlanSetting enablePlanInfo = planSettingList.get(0);
        if (enablePlanInfo == null) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST);
        }
        Integer wxPayFunctionSort = enablePlanInfo.getPlanChargeShopSort();
        if (wxPayFunctionSort == null || wxPayFunctionSort <= 0
                || wxPayFunctionSort > wxPayFunctionsList.size() + 1) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        // 获取用户选择的商户
        WxPayFunctions wxPayFunction = wxPayFunctionsList.get(wxPayFunctionSort - 1);

        //缴费项
        divideReqList = chargeCategoryOperation(stu_id,req.getChargeCategoryRecordList());

        //支付所需的信息
        recordReq.setStuId(studentInfo.getId());
        recordReq.setPlanId(planId);
        recordReq.setType(RX_REGISTRATION_CHARGE_PAYMENT_RECORD_TYPE_CONFIRM);
        recordReq.setOpenId(req.getOpenId());
        recordReq.setWxPayFunction(wxPayFunction);
        recordReq.setMode(RX_REGISTRATION_CHARGE_PAYMENT_RECORD_MODE_ONLINE);
        recordReq.setDivideReqList(divideReqList);
        RxRegistrationPrepayPaymentResp prepayPaymentResp = paymentUtil.payment(recordReq);
        if (prepayPaymentResp == null) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PAYMENT_FAIL);
        }
        return CommonResult.success(prepayPaymentResp);
    }

    /**
     * @description 收费项处理  校验并输出收费项集合
     * @create 2024/5/21
     * @author dxn
     */
    private List<RxRegistrationChargePaymentCategoryDivideReq> chargeCategoryOperation(String stu_id,
                                                                                       List<RxRegistrationChargeCategoryRecordReq> chargeCategoryRecordList) {
        List<RxRegistrationChargePaymentCategoryDivideReq> divideList = new ArrayList<>();

        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(stu_id);

        //获取收费项设置列表
        List<RxRegistrationPlanChargeCategoryResp> pendingChargeCategoryList = getChargeCategoryRespList(studentInfo.getPlanId(), studentInfo);

        for (RxRegistrationPlanChargeCategoryResp pendingChargeCategory : pendingChargeCategoryList) {
            //匹配与系统收费项集合进行匹配
            List<RxRegistrationChargeCategoryRecordReq> filterList = chargeCategoryRecordList
                    .stream()
                    .filter(record -> record.getMainId().equals(pendingChargeCategory.getChargeCategoryId()))
                    .collect(Collectors.toList());
            //判断是否必填
            if (pendingChargeCategory.getIsRequired()) {
                //必填 且未填写 报错
                if (filterList.size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_NOT_FILL));
                }
            }

            //不必填 且未填写 跳过
            if (filterList.size() < 1) {
                continue;
            }

            //校验已填写单选 多选
            RxRegistrationChargeCategoryRecordReq filterRecord = filterList.get(0);
            if (pendingChargeCategory.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_SIGNAL) {
                if (filterRecord.getChildList().size() != 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_FILL_ERROR));
                }

                String childId = filterRecord.getChildList().get(0).getChildId();
                addChargeCategoryToList(divideList, pendingChargeCategory, childId);
            } else if (pendingChargeCategory.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_MULTIPLE) {
                if (filterRecord.getChildList().size() > pendingChargeCategory.getChildList().size()
                        || filterRecord.getChildList().size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_FILL_ERROR));
                }

                for (RxRegistrationChargeCategoryRecordDetailReq childRecord : filterRecord.getChildList()) {
                    String childId = childRecord.getChildId();
                    addChargeCategoryToList(divideList, pendingChargeCategory, childId);
                }
            } else {
                addChargeCategoryToList(divideList, pendingChargeCategory, null);
            }
        }

        //删除缴费项记录
        if (studentInfo.getAdvanceStatus() != REGISTRATION_STATUS_FINISH
                || studentInfo.getConfirmStatus() != REGISTRATION_STATUS_FINISH) {
            LambdaQueryWrapper<RxRegistrationChargeCategoryRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RxRegistrationChargeCategoryRecord::getStuId, stu_id)
                    .and(wrapper -> {  //TODO
                        if (studentInfo.getAdvanceStatus() != REGISTRATION_STATUS_FINISH) {
                            wrapper.eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_ADVANCE);
                        }
                        if (studentInfo.getConfirmStatus() != REGISTRATION_STATUS_FINISH) {
                            wrapper.or().eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_CONFIRM);
                        }
                    });
            rxRegistrationChargeCategoryRecordMapper.delete(queryWrapper);
        }
        //保存记录
        List<RxRegistrationChargeCategoryRecord> recordList = divideList.stream()
                .map(divide -> {
                    RxRegistrationChargeCategoryRecord record = new RxRegistrationChargeCategoryRecord();
                    record.setStuId(stu_id);
                    record.setAppType(APP_TYPE_CONFIRM);  //TODO
                    record.setMainId(divide.getCategoryId());
                    record.setMainName(divide.getCategoryName());
//                    record.setMainType(pendingChargeCategoryList.stream()
//                            .filter(pendingChargeCategory -> pendingChargeCategory.getChargeCategoryId().equals(divide.getCategoryId())));
                    record.setPrice(divide.getAmount());
                    record.setChildId(divide.getCategoryDetailId());
                    record.setChildName(divide.getCategoryDetailName());
                   return record;
                })
                .collect(Collectors.toList());
        rxRegistrationChargeCategoryRecordService.saveBatch(recordList);
        return divideList;
    }

    private void addChargeCategoryToList(List<RxRegistrationChargePaymentCategoryDivideReq> divideList,
                                         RxRegistrationPlanChargeCategoryResp pendingChargeCategory,
                                         String childId) {
        RxRegistrationChargePaymentCategoryDivideReq divideReq = new RxRegistrationChargePaymentCategoryDivideReq();
        divideReq.setCategoryId(pendingChargeCategory.getChargeCategoryId());
        divideReq.setCategoryName(pendingChargeCategory.getChargeCategoryName());
        if (!isNullOrEmpty(childId)) {
            List<RxRegistrationChargeCategoryDetailResp> childFilterRecordList = pendingChargeCategory.getChildList()
                    .stream()
                    .filter(child -> child.getChargeCategoryId().equals(childId))
                    .collect(Collectors.toList());
            if (childFilterRecordList.size() < 1) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_CHILD_ERROR));
            }
            divideReq.setCategoryDetailId(childFilterRecordList.get(0).getChargeCategoryId());
            divideReq.setCategoryDetailName(childFilterRecordList.get(0).getChargeCategoryName());
            divideReq.setAmount(childFilterRecordList.get(0).getChargeCategoryPrice());
        } else {
            divideReq.setAmount(pendingChargeCategory.getChargeCategoryPrice());
        }
        divideList.add(divideReq);
    }


}
